from django.shortcuts import render, HttpResponse, redirect
from app01 import models

# Create your views here.

def index(request):
    return HttpResponse('欢迎使用')

def user_list(request):
    # 根据app的注册顺序，在每个app下的templates目录中进行寻找模板（前段页面）
    return render(request, "user_list.html")

def news(request):
    # 向这个地址发送请求：http://www.chinaunicom.com/api/article/NewsByIndex/2/2022/12/news
    import requests
    url = 'http://www.chinaunicom.com/api/article/NewsByIndex/2/2022/12/news'
    header = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3775.400 QQBrowser/10.6.4208.400'
    }
    res = requests.get(url=url, headers=header)
    data_list = res.json()
    print(data_list)

    return render(request, 'news.html', {'news_list': data_list})

def something(request):
    # request是一个对象，封装了用户发送过来的所有请求相关数据
    # 1. 获取请求的方式：GET/POST
    print(request.method)

    # 2. 在url上传递值
    print(request.GET)

    # 3. 在请求体中提交数据
    print(request.POST)

    # 1. 直接将响应字符串内容返回给请求者
    # return HttpResponse('返回内容')

    # 2. 读取模板/html内容+渲染再返回给请求者
    # return render(request, 'something.html', {"title": "123"})

    # 3. 返回重定向结果给请求者
    return redirect('http://www.baidu.com')

def login(request):
    if request.method == "GET":
        return render(request, 'login.html')
    else:
        # POST请求，获取用户提交的数据
        print(request.POST)
        username = request.POST.get('user')
        password = request.POST.get('password')
        if username == 'cxz' and password == '123':
            return redirect('http://www.baidu.com')
        # return HttpResponse('登录失败')
        return render(request, 'login.html', {"error_message": "用户名或密码错误"})

def orm(request):
    # models.UserInfo.objects.create(name='cxz', password='123', age=18)
    # models.UserInfo.objects.create(name='zhansan', password='123', age=18)
    # models.UserInfo.objects.create(name='lisi', password='123', age=18)

    # models.UserInfo.objects.filter(id=3).delete()

    # data_list = models.UserInfo.objects.all()
    # print(data_list)

    models.UserInfo.objects.filter(name='zhansan').update(age=22)
    return HttpResponse('成功')

def info_list(request):
    data_list = models.UserInfo.objects.all()
    return render(request, 'info_list.html', {'data_list': data_list})

def info_add(request):
    if request.method == 'GET':
        return render(request, 'info_add.html')
    name = request.POST.get('user')
    password = request.POST.get('password')
    age = request.POST.get('age')

    models.UserInfo.objects.create(name=name, password=password, age=age)
    return redirect('/info/list/')

def info_delete(request):
    nid = request.GET.get('nid')
    models.UserInfo.objects.filter(id=nid).delete()
    return redirect('/info/list/')